package com.park.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.park.client.model.action.ActionModel;
import com.park.client.model.user.UserModel;
import com.park.client.service.action.ActionService;
import com.park.common.constant.Constant;
import com.park.common.empty.StringUtils;
import com.park.web.util.SessionUtil;


public class LoginFilter implements Filter{

	private String paramValues;
	
	private ActionService actionService;
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();
		String contextPath = request.getContextPath()+"/";//项目访问根路径
		String[] urls = paramValues.split(",");
		HttpSession session = request.getSession();
		UserModel user = SessionUtil.getSessionUser(session);
		if(uri.contains("/public") 
				|| uri.contains("/logout")  
				|| uri.indexOf("login") != -1
				|| contextPath.equals(uri)
				|| StringUtils.containsStrInArr(uri, urls)
				|| user != null){
			//非管理员禁止进入管理员界面
			if(user !=null && Constant.ADMIN_TYPE_ID != user.getIsAdmin() && uri.contains("/admin")){
				response.sendRedirect(contextPath+"user/index");
			}else{
				chain.doFilter(request, response);
			}
		}else{
			String actionUrl = uri.substring(contextPath.length(), uri.length());
			ActionModel action = actionService.selectByUrl(actionUrl);
			if(action != null){
				chain.doFilter(request, response);
			}else{
				response.sendRedirect(contextPath+"public/user/login");
			}
		}
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		paramValues = filterConfig.getInitParameter("exclusions");
		ServletContext sc = filterConfig.getServletContext(); 
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean("actionService") != null && actionService == null){
        	actionService = (ActionService) cxt.getBean("actionService");    
        }
	}

	@Override
	public void destroy() {
		paramValues = null;
	}
	

}
